// 在微信小程序的 Page 中定义
Page({
  data: {
  userInfoLocal:null,
    userStore: userStore,
    step: 1,
    showOverlay: false,
    activeIndex: 0,
    hoveredTaskIndex: -1,
    clickedTaskIndex: -1,
    totalTasks: 0,
    completedTasks: 0,
    pendingTask: [],
    assessmentRecords: [],
    recordService:[],
    Task: {
      pageNo: 1,
      pageSize: 5
    },
    Record: {
      pageNo: 1,
      pageSize: 5
    },
    Recordtotal: 0,
    Tasktotal: 0,
    boy: '../../pages/statics/img/student/boy.png', // 本地图片路径
    girl: '../../pages/statics/img/student/girl.png'
  },

  onLoad() {
    const hasSeenOverlay = wx.getStorageSync('hasSeenOverlay');
    if (!hasSeenOverlay) {
      this.setData({
        showOverlay: true
      });
    }
    console.log("111")
    console.log("1");
    console.log("recordService-onLoad", recordService);
      
    const userInfoLocal = wx.getStorageSync('userInfoLocal');
    if (userInfoLocal) {
      const parsedUserInfo = JSON.parse(userInfoLocal);  // 如果存在，则解析并设置到 data 中
      this.setData({
        userInfoLocal: parsedUserInfo  // 将数据设置到页面的 data 中
      });
      console.log("userInfoLocal:", parsedUserInfo); // 输出 userInfoLocal
    } else {
      console.log("没有找到存储的用户信息");
    }


    const app = getApp()
    // 应用启动时从本地存储加载用户信息
    // this.globalData.userStore.getUser();
    //app.globalData.userStore.getUser()
    console.log(app.globalData)
    const appGlobalData = app.globalData;
    const userInfo = appGlobalData.userInfo;
    // const userInfo = app.globalData.userInfo;
    console.log("appGlobalData==",appGlobalData)
    console.log("index里面的用户信息",userInfo); // 获取到的 userInfo 数据
    // console.log("app.globalData",app.globalData.userStore)
    this.fetchPendingTask();
    this.fetchAssessmentRecords();
    //this.fetchrecordService();
    console.log("测试用户名",userStore.User.name)
    console.log("测试app:",app.globalData);
  },

  onShow() {
    // 每次页面展示时刷新数据
    this.fetchPendingTask();
    this.fetchAssessmentRecords();
   // this.fetchrecordService();

   // 在页面的 onLoad 或 onShow 方法中动态修改导航栏颜色
wx.setNavigationBarColor({
  frontColor: '#ffffff',  // 导航栏前景色，包括标题、按钮等的颜色（白色）
  backgroundColor: '#56DE68',  // 导航栏背景颜色
  animation: {  // 动画效果，可选
    duration: 400,  // 动画时长（ms）
    timingFunc: 'easeInOut'  // 动画的效果函数
  }
});
  },

  nextStep() {
    this.setData({
      step: this.data.step + 1
    });
  },

  finish() {
    wx.setStorageSync('hasSeenOverlay', 'true');
    this.setData({
      showOverlay: false
    });
    wx.navigateTo({
      url: '/pages/form/form'
    });
  },

  onSizeChange(e) {
    const size = e.detail.value;
    this.setData({
      'Task.pageNo': 1,
      'Task.pageSize': size
    });
    this.fetchPendingTask();
  },

  onCurrentChange(e) {
    const page = e.detail.value;
    this.setData({
      'Task.pageNo': page
    });
    this.fetchPendingTask();
  },
 
  async fetchPendingTask() {
    const app = getApp(); //获取小程序实例
    const token = app.globalData.accessToken||'';//直接从全局数据中获取token
    console.log("token==",token)
    const headers = {
      'content-type': 'application/json',
      'token': token
    };
    const self = this
    try {
      await wx.request({
        // url: 'http://106.53.70.21:2626/api/v2/survey/queryMySurveyList', // 替换成实际 API 地址
        url: 'http://202.192.19.106:8080/api/v2/survey/queryMySurveyList', // 替换成实际 API 地址
        method: 'POST',
        data: {
          pageNo: 1,
          pageSize: 10
          // pageNo: this.data.Task.pageNo,
          // pageSize: this.data.Task.pageSize
        },
        header: headers,

        success: function (res) {
          console.log("res===",res)
          const result = res
          console.log("result=",result)
          const pendingTasks = result.data.data.result;
          const arr1 = [];
          pendingTasks.forEach((task) => {
          task.beginAt = new Date(task.beginAt);
          task.endAt = new Date(task.endAt);
          task.beginAtFormatted = self.formatDate(task.beginAt);
          task.endAtFormatted = self.formatDate(task.endAt);
          arr1.push({
            id: task.id,
            name: task.name,
            deadline: self.formatDate(task.endAt),
            beginAt: self.formatDate(task.beginAt),
            beginAtDate: task.beginAt,
            endAtDate: task.endAt
          });
      });
      self.setData({
        pendingTask: arr1,
        Tasktotal: result.data.data.total
      });
        },
        fail: function (error) {
          console.log("error=",error)
        }
      })
      // console.log("result=",result)
      // const pendingTasks = result.data.data.result;
      // const arr1 = [];
      // pendingTasks.forEach(task => {
      //   task.beginAt = new Date(task.beginAt);
      //   task.endAt = new Date(task.endAt);
      //   task.beginAtFormatted = this.formatDate(task.beginAt);
      //   task.endAtFormatted = this.formatDate(task.endAt);
      //   arr1.push({
      //     id: task.id,
      //     name: task.name,
      //     deadline: this.formatDate(task.endAt),
      //     beginAt: this.formatDate(task.beginAt),
      //     beginAtDate: task.beginAt,
      //     endAtDate: task.endAt
      //   });
      // });
      // this.setData({
      //   pendingTask: arr1,
      //   Tasktotal: result.data.data.total
      // });
    } catch (error) {
      console.error('Error fetching pending tasks:', error);
    }
  },
  async fetchAssessmentRecords() {
    const app = getApp(); // 获取小程序实例
    const token = app.globalData.accessToken || ''; // 从全局数据中获取 token
    const headers = {
      'content-type': 'application/json',
      'token': token
    };
    
    try {
      const recordService = await new Promise((resolve, reject) => {
        wx.request({
          url: 'http://202.192.19.106:8080/api/v2/user-answer/submit-record',
          data: {
            pageNo: 1,
            pageSize: 10
          },
          header: headers,
          method: 'GET',
          success(res) {
            if (res.statusCode === 200) {
              resolve(res.data.data.result); // 请求成功，返回数据
            } else {
              reject('请求失败');
            }
          },
          fail(error) {
            reject(error); // 请求失败，返回错误信息
          }
        });
      });
  
      console.log("recordService=", recordService);
      this.setData({
        recordService: recordService
      });
  
    } catch (error) {
      console.log("error=", error);
    }
  },


  formatDate(date) {
    const year = date.getFullYear();
    const month = (date.getMonth() + 1).toString().padStart(2, '0');
    const day = date.getDate().toString().padStart(2, '0');
    const hours = date.getHours().toString().padStart(2, '0');
    const minutes = date.getMinutes().toString().padStart(2, '0');
    const seconds = date.getSeconds().toString().padStart(2, '0');
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  },

  handleTaskClick(e) {
    const index = e.currentTarget.dataset.index;
    this.setData({
      clickedTaskIndex: index
    });
    if (this.data.pendingTask[index].disabled) return;

    const questionnaireId = this.data.pendingTask[index].id;
    wx.navigateTo({
      url: `/pages/questionnaire/questionnaire?id=${questionnaireId}`
    });
  },

  handleTaskHover(e) {
    const index = e.currentTarget.dataset.index;
    if (this.data.pendingTask[index].disabled) return;
    this.setData({
      hoveredTaskIndex: index
    });
  },

  handleTaskLeave() {
    this.setData({
      hoveredTaskIndex: -1
    });
  },


});
import {
  userStore
} from '../../stores/userStore';
import {
  get,post
} from './request.js'
// 获取用户 token



const User = {
  token: " eyJhbGciOiJIUzI1NiJ9.eyJ1c2VyQ29udGV4dERUTyI6eyJpZCI6MSwic2Nob29sSWQiOm51bGwsImdyYWRlSWQiOm51bGwsImNsYXNzSWQiOm51bGwsImNpdHlJZCI6bnVsbCwiZGlzdHJpY3RJZCI6bnVsbCwicm9sZUxldmVsIjowfSwiZXhwIjoxNzExODk4OTE1fQ.l4yp-iJGfhuEWXd2sm1GIPpsBmDs0ZB6oxw47iIuTOIA"



};

// 新建问卷
export const scaleCreateSurveyService = (data) => {
  console.log(data, '新建问卷参数');
  wx.request({
    url: '/api/v2/survey/createSurvey',
    method: 'POST',
    data: data,
    header: {
      token: User.token
    },
    success(res) {
      wx.showToast({
        title: '创建问卷成功',
        icon: 'success'
      });
    },
    fail(error) {
      wx.showToast({
        title: '创建问卷失败，请稍后重试',
        icon: 'error'
      });
    }
  });
};

// 分页查询所有问卷
export const scaleGetsurveyListService = (data) => {
  return new Promise((resolve, reject) => {
    wx.request({
      url: 'api/v2/survey/querySurveyList',
      method: 'POST',
      data: data,
      header: {
        token: User.token
      },
      success(res) {
        resolve(res);
      },
      fail(error) {
        reject(error);
      }
    });
  });
};

// 查询问卷的所有信息
export const scaleGetSurveyDetailService = (surveyId) => {
  return new Promise((resolve, reject) => {
    wx.request({
      url: '/api/v2/survey/querySurveyInfo',
      method: 'GET',
      header: {
        token: User.token
      },
      data: {
        surveyId: surveyId
      },
      success(res) {
        resolve(res);
      },
      fail(error) {
        reject(error);
      }
    });
  });
};

// 更新问卷
export const userUpdateSurveyService = (data) => {
  console.log(data, '修改问卷参数');
  wx.request({
    url: 'api/v2/survey/updateSurvey',
    method: 'PUT',
    data: data,
    header: {
      token: User.token
    },
    success(res) {
      wx.showToast({
        title: '修改问卷成功',
        icon: 'success'
      });
    },
    fail(error) {
      wx.showToast({
        title: '修改问卷失败，请稍后重试',
        icon: 'error'
      });
    }
  });
};

// 删除问卷
export const surveyDeleteService = (ids) => {
  return new Promise((resolve, reject) => {
    wx.request({
      url: 'api/v2/survey/deleteSurvey',
      method: 'DELETE',
      header: {
        token: User.token
      },
      data: {
        ids: ids
      },
      success(res) {
        resolve(res);
      },
      fail(error) {
        reject(error);
      }
    });
  });
};

// 发布或撤回问卷
export const surveyOpenService = (id, isOpen) => {
  return new Promise((resolve, reject) => {
    wx.request({
      url: `api/v2/survey/isOpen/${id}/${isOpen}`,
      method: 'PUT',
      header: {
        token: User.token
      },
      success(res) {
        resolve(res);
      },
      fail(error) {
        reject(error);
      }
    });
  });
};

// 查询评测记录
export const recordService = (pageNo, pageSize) => {
  return new Promise((resolve, reject) => {
    wx.request({
      url: 'http://202.192.19.106:8080/api/v2/user-answer/submit-record',
      method: 'GET',
      data: {
        pageNo: 1,
        pageSize: 10
      },
      success(res) {
        resolve(res);
        console.log("测评记录：",res);
      },
      fail(error) {
        reject(error);
      }
    });
  });
};